﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.NotificationTypes.Interfaces;
using Microhard.NotificationTypes.Models;
using Microhard.NotificationTypes.DataAccess;
using Microhard.Core.DBUtility;
using Microhard.NotificationTypes.DTO;
using Microhard.Core;

namespace Microhard.NotificationTypes.Impls
{
    /// <summary>
    /// 站内提醒
    /// </summary>
    public class InternalSiteNotification : INotification
    {
        public List<NotificationModel> Notify()
        {
            var userid = scope.CurrentUserID;
            List<NotificationModel> rtn = new List<NotificationModel>();
            ChatDBDataContext db = new ChatDBDataContext();
            var sended = from n in db.MicroHard_ChatReceivers
                         where n.ReceiverID == userid
                         && n.Status == (int)ChatStatus.Sended
                         select n;
            var toNotfi = sended.ToList();
            if (sended.Count() > 0)
            {
                foreach (var s in sended)
                {
                    s.Status = (int)ChatStatus.Notified;
                }
                try
                {
                    db.SubmitChanges();
                }
                catch (Exception ex)
                {
                    Log.Error("InternalSiteNotification.Notify", ex);
                }

                rtn = (from n in toNotfi
                       select new NotificationModel
                       {
                           ChatID = n.ChatID.Value,
                           Content = new NotificationContent { Message = n.MicroHard_Chat.Data },
                           Receiver = new User { ID = n.ReceiverID.Value, UserName = n.ReceiverName },
                           ReceivingTime = n.ReceivedTime.Value,
                           Sender = new User { ID = n.MicroHard_Chat.SenderID.Value, UserName = n.MicroHard_Chat.SenderName },
                           SendingTime = n.MicroHard_Chat.SendTime.Value,
                           Status = n.Status.Value,
                           Type = NotificiationType.Internal
                       }).ToList();
            }
            return rtn;
        }

        #region IRepository<NotificationModel> Members

        public ExecutedResult Add(NotificationModel model)
        {
            ExecutedResult rtn = new ExecutedResult();
            ChatDBDataContext db = new ChatDBDataContext();
            MicroHard_Chat toAdd = new MicroHard_Chat();
            toAdd.ChatID = model.ChatID;
            toAdd.Data = model.Content.Message;
            if (model.IsSysSender)
            {
                toAdd.SenderID = model.Sender.ID;
                toAdd.SenderName = model.Sender.UserName;
            }
            else
            {
                toAdd.SenderID = scope.CurrentUserID;
                toAdd.SenderName = scope.CurrentUserName;
            }
            toAdd.SendTime = DateTime.Now;
            foreach (var s in model.ReceiverToAdd)
            {
                MicroHard_ChatReceiver cr = new MicroHard_ChatReceiver();
                cr.ReceiverID = s.ID;
                cr.ReceivedTime = DateTime.Now;
                cr.RecPKID = Guid.NewGuid();
                cr.ReceiverName = s.UserName;
                cr.Status = (int)ChatStatus.Sended;
                toAdd.MicroHard_ChatReceivers.Add(cr);
            }
            db.MicroHard_Chats.InsertOnSubmit(toAdd);
            try
            {
                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                rtn.ErrorMsg.Add("InternalSiteNotification.Add", ex.Message);
            }
            return rtn;
        }

        public ExecutedResult Update(NotificationModel model)
        {
            ExecutedResult result = new ExecutedResult();
            ChatDBDataContext db = new ChatDBDataContext();
            var toUpdate = db.MicroHard_ChatReceivers.SingleOrDefault(d => d.ReceiverID == model.Receiver.ID && d.ChatID == model.ChatID);
            if (toUpdate != null)
            {
                toUpdate.Status = (int)ChatStatus.Readed;
                try
                {
                    db.SubmitChanges();
                }
                catch (Exception ex)
                {
                    result.ErrorMsg.Add("InternalSiteNotification.Update", ex.Message);
                }
                return result;

            }
            return result;
        }

        public ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            ChatDBDataContext db = new ChatDBDataContext();
            var toDeltes = from b in db.MicroHard_ChatReceivers
                           where ids.Contains(b.MicroHard_Chat.ChatID) && b.ReceiverID == scope.CurrentUserID
                           select b;
            foreach (var d in toDeltes)
            {
                db.MicroHard_ChatReceivers.DeleteOnSubmit(d);
            }
            try
            {
                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                result.ErrorMsg.Add("InternalSiteNotification.Delete", ex.Message);
            }
            return result;
        }

        public ExecutedResult Delete(NotificationModel model)
        {
            throw new NotImplementedException();
        }

        public NotificationModel GetModelByID(Guid id)
        {
            throw new NotImplementedException();
        }

        public NotificationModel GetModelByModel(NotificationModel model)
        {
            throw new NotImplementedException();
        }

        public List<NotificationModel> Query(NotificationModel Model, int pageIndex, int pageSize, out int totalCount)
        {
            ChatDBDataContext db = new ChatDBDataContext();
            if (Model.Content != null && !string.IsNullOrEmpty(Model.Content.Message))
            {

            }
            var entities = from n in db.MicroHard_Chats
                           from r in n.MicroHard_ChatReceivers
                           where (scope.PKID.Contains(n.ChatID) || r.ReceiverID == scope.CurrentUserID)
                           select r;
            totalCount = entities.Count();
            var pagedEntities = entities.OrderByDescending(p => p.ReceivedTime.Value).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            return pagedEntities.Select(p => new NotificationModel
            {
                ChatID = p.MicroHard_Chat.ChatID,
                Content = new NotificationContent { Message = p.MicroHard_Chat.Data },
                Receiver = new User { ID = p.ReceiverID.Value, UserName = p.ReceiverName },
                ReceivingTime = p.ReceivedTime.Value,
                Sender = new User { ID = p.MicroHard_Chat.SenderID.Value, UserName = p.MicroHard_Chat.SenderName },
                SendingTime = p.MicroHard_Chat.SendTime.Value,
                Status = p.Status.Value,
                Type = NotificiationType.Internal
            }).ToList();
        }

        public List<NotificationModel> Query(NotificationModel Model)
        {
            throw new NotImplementedException();
        }

        public ScopeResult scope
        {
            set;
            get;
        }

        #endregion
    }
}
